<template>
  <view class="st-u-comment-subject-detail">
    <view class="comment">
      <!--      详情顶部区域-->
      <view class="top">
        <!--        左侧用户信息-->
        <view class="left">
          <view class="heart-photo">
            <!--头像信息-->
            <u-avatar :src="commentSubject.ownerUserAvatar" @tap="$emit('detailAvatarClick',commentSubject)" mode="circle"
                      :show-sex="!!detailGenderResolve(commentSubject)" :sex-icon="gender[detailGenderResolve(commentSubject)]" ></u-avatar>
          </view>
          <view class="user-info">
            <view class="name">{{ commentSubject.ownerUserNickname }}</view>
            <view class="date">{{ commentSubject.timeAt }}</view>
          </view>
        </view>
        <!--        右侧，点赞-->
        <view class="right st-flex" >
          <view class="detail-reply">
            <u-icon class="detail-reply-icon" name="chat"  :size="30" @click="detailReplyClick(commentSubject)"></u-icon>
          </view>
          <view :class="{ highlight: commentSubject.isMeHasStared }">
            <text>{{ commentSubject.starCount }}</text>
            <u-icon v-if="!commentSubject.isMeHasStared" name="thumb-up" class="like" color="#9a9a9a" :size="30" @click="starOrCancel(commentSubject)"></u-icon>
            <u-icon v-if="commentSubject.isMeHasStared" name="thumb-up-fill" class="like" :size="30" @click="starOrCancel(commentSubject)"></u-icon>
          </view>
        </view>
      </view>
      <!--      详细内容-->
      <view class="content">{{ commentSubject.content }}</view>

      <!--点赞列表-->
      <view v-if="commentSubject.latestCommentSubjectStars && commentSubject.latestCommentSubjectStars.records.length > 0" class="st-flex star-box"
            style="margin-top: 20rpx;padding: 20rpx; background-color: #f3f3f5;" :class="{'star-box-border-bottom':commentSubject.latestCommentSubjects && commentSubject.latestCommentSubjects.records.length > 0}">
        <!-- 点赞人的头像-->
        <template v-for="(starItem,index) in commentSubject.latestCommentSubjectStars.records">
          <u-image @tap="detailStarAvatarClick(commentSubject,starItem)"  :src="starItem.ownerUserAvatar" :width="35" :height="35" shape="circle" mode="aspectFill" :key="index">
          </u-image>
        </template>
        <!--        详情点赞简单列出-->
        <view class="all-star" @tap="detailToAllStar(commentSubject)" v-if="commentSubject.starCount > 0">
          <text> {{ commentSubject.starCount }}人赞过</text>
          <u-icon class="more" name="arrow-right" :size="20"></u-icon>
        </view>
      </view>
    </view>
    <!--    以下为回复列表-->
    <view class="all-reply">
      <view class="all-reply-top">全部回复（{{ commentHierarchicalPage.total }}）</view>
      <view class="item" v-for="(item, index) in commentHierarchicalList" :key="index">
        <view class="comment">
          <view class="top">
            <view class="left">
              <view class="heart-photo">
                <!--头像信息-->
                <u-avatar size="mini" @tap="replyAvatarClick(item)" :src="item.ownerUserAvatar" mode="circle"
                          :show-sex="!!replyGenderResolve(item)" :sex-icon="gender[replyGenderResolve(item)]" ></u-avatar>
              </view>
              <!-- 头像下方的其它信息-->
              <view class="user-info">
                <view class="name">{{ item.ownerUserNickname }}</view>
                <view class="date">{{ item.timeAt }}</view>
              </view>
            </view>
            <!-- 右侧的点赞-->
            <view class="right"  :class="{ highlight: item.isMeHasStared }">
              <view class="num">{{ item.starCount }}</view>
              <u-icon v-if="!item.isMeHasStared" name="thumb-up" class="like" :size="30" color="#9a9a9a" @click="replyStarOrCancel(item)"></u-icon>
              <u-icon v-if="item.isMeHasStared" name="thumb-up-fill" class="like" :size="30" @click="replyStarOrCancel(item)"></u-icon>
            </view>
          </view>

          <!-- 回复内容-->
          <view class="content">{{ item.content }}</view>

          <!--点赞列表-->
          <view v-if="item.latestCommentHierarchicalStars && item.latestCommentHierarchicalStars.records.length > 0" class="st-flex star-box"
                style="margin-top: 20rpx;padding: 20rpx; background-color: #f3f3f5;" :class="{'star-box-border-bottom':item.latestCommentHierarchicalStars && item.latestCommentHierarchicalStars.records.length > 0}">
            <!-- 点赞人的头像-->
            <template v-for="(starItem,index) in item.latestCommentHierarchicalStars.records">
              <u-image @tap="replyStarAvatarClick(item,starItem)"  :src="starItem.ownerUserAvatar" :width="35" :height="35" shape="circle" mode="aspectFill" :key="index">
              </u-image>
            </template>
            <view class="all-star" @tap="replyToAllStar(item)" v-if="item.starCount > 0">
              {{ item.starCount }}人赞过
              <u-icon class="more" name="arrow-right" :size="20"></u-icon>
            </view>
          </view>

          <!-- 回复的下级回复内容-->
          <view class="reply-box" v-if="item.latestCommentHierarchicals && item.latestCommentHierarchicals.records.length > 0">
            <view class="reply-box-item" v-for="(hierarchicalItem, hierarchicalIndex) in item.latestCommentHierarchicals.records" :key="hierarchicalIndex">
              <view class="st-flex">
                <!-- 下级回复头像-->
                <u-image @tap="replyReplyCommentHierarchicalAvatarClick(item,hierarchicalItem)" :src="hierarchicalItem.ownerUserAvatar" :width="35" :height="35" shape="circle" mode="aspectFill" style="margin-bottom: -3rpx;">
                </u-image>
                <text class="username">{{ hierarchicalItem.ownerUserNickname }}</text>
              </view>
              <!-- 下级回复内容-->
              <view class="text">
                <text class="content">{{ hierarchicalItem.content }}</text>
                <text class="reply" @tap="replyReplycommentReplyClick(item,hierarchicalItem)">{{ hierarchicalItem.commentCount>0 ? hierarchicalItem.commentCount : ''}}回复<u-icon class="more" name="arrow-right" :size="20"></u-icon></text>
              </view>
            </view>
            <view class="sub-all-reply" @tap="replyToAllReplyClick(item)" v-if="item.commentCount > 0">
              共{{  item.commentCount }}条回复
              <u-icon class="more" name="arrow-right" :size="26"></u-icon>
            </view>
          </view>
          <view class="bottom">
            {{ item.timeAt }}
            <view class="reply" @click="replyReplyClick(item)">回复</view>
          </view>
        </view>
      </view>
    </view>

    <stULoadmore ref="loadMore" :ready="loadCommentHierarchicalForSubject" @loadmore="loadCommentHierarchicalForSubject"></stULoadmore>

  </view>
</template>

<script>
import CommentSubjectUrl from "../../../../pc/subject/CommentSubjectUrl";
import CommentHierarchicalUrl from "../../../../pc/hierarchical/CommentHierarchicalUrl.js";
import stULoadmore from '../../../../../../common/web/components/app/uni-app/uview/st-u-loadmore/st-u-loadmore.vue'
import CommentSubjectStarUrl from "../../../../pc/subject/CommentSubjectStarUrl";
import CommentHierarchicalStarUrl from '../../../../pc/hierarchical/CommentHierarchicalStarUrl.js'
export default {
  components: {stULoadmore},
  props: {
    /**
     * commentSubjectId
     */
    commentSubjectId: {
      type: String,
      required: true
    },
    // 分组标识
    groupFlag: {
      type: String,
    },
    // 详情对应的获取性别
    detailGenderResolve: {
      type: Function,
      default: (commentSubject)=>{
        let r = ''
        if(commentSubject.ext){
          return commentSubject.ext.genderDictValue
        }
        return r
      }
    },
    // 详情对应的获取性别
    replyGenderResolve: {
      type: Function,
      default: (commentHierarchical)=>{
        let r = ''
        if(commentHierarchical.ext){
          return commentHierarchical.ext.genderDictValue
        }
        return r
      }
    },
    // 当前登录用户的id，如果不传默认取vuex_userInfo.id
    userId: {
      type: String
    }
  },
  data() {
    return {
      commentHierarchicalList: [],
      commentHierarchicalPage: {total: 0},
      /**
       * 评论
       */
      commentSubject: {},
      // 查询参数
      commentHierarchicalForSubjectQuery: {
        current: 1,
        subjectId: this.commentSubjectId,
        groupFlag: this.groupFlag
      }
    };
  },
  mounted() {
    this.loadCommentSubject()
  },
  methods: {
    loadCommentSubject(){
      let pathParam = {id: this.commentSubjectId}
      this.$http.get(this.$stStringTools.replaceb(CommentSubjectUrl.detail,pathParam),{params: {groupFlag: this.groupFlag}}).then(res => {
        this.commentSubject = res.data
      })
    },
    // 加载数据
    loadCommentHierarchicalForSubject(refresh,callback=()=>{}) {
      if(!refresh && this.$refs.loadMore && !this.$refs.loadMore.canLoad()){
        if(callback){
          callback()
        }
        return
      }
      this.$http.get(CommentHierarchicalUrl.getAvailableForSubjectPage,{params:this.commentHierarchicalForSubjectQuery}).then(res => {
        if (this.commentHierarchicalForSubjectQuery.current == 1) {
          this.commentHierarchicalList = []
        }
        res.data.records.forEach(item =>{
          this.commentHierarchicalList.push(item)
        });
        this.commentHierarchicalForSubjectQuery.current = res.data.current + 1
        this.commentHierarchicalPage.total = res.data.total
        this.$refs.loadMore.loaded(res.data)
      }).catch((error)=>{
        this.$u.toast('抱歉系统出错误了')
        console.error(error)
        this.$refs.loadMore.loadError()
      }).finally(()=>{
        if(callback){
          callback()
        }
      })
    },
    // 刷新数据
    refreshCommentHierarchicalForSubject(callback=()=>{}){
      this.commentHierarchicalForSubjectQuery.current = 1
      this.loadCommentHierarchicalForSubject(true,callback)
    },
    // 详情用户头像事件
    detailAvatarClick(commentSubject){
      this.$emit('detailAvatarClick', commentSubject)
    },
    // 点击点赞区头像事件
    detailStarAvatarClick(commentSubject,starItem){
      this.$emit('detailStarAvatarClick', {commentSubject,starItem})
    },
    // 点击全部点赞事件
    detailToAllStar(commentSubject){
      this.$emit('detailToAllStarClick',commentSubject)
    },
    // 点赞或取消
    starOrCancel(commentSubject){
      if (commentSubject.isMeHasStared) {
        // 最后面的参数 true 表示立即执行
        this.$u.debounce(()=>{this.doCancelStar(commentSubject)}, 800,true)
      }else {
        this.$u.debounce(()=>{this.doStar(commentSubject)}, 800,true)
      }
    },
    // 点赞发起请求
    doStar(commentSubject){
      this.checkLogin().then(()=>{
        let data = {
          commentSubjectId: commentSubject.id,
          groupFlag: this.groupFlag
        }
        this.$http.post(CommentSubjectStarUrl.addStar,data).then((res)=>{
          commentSubject.isMeHasStared = true
          commentSubject.starCount += 1
          this.prependStar(commentSubject,res.data)
        })
      })
    },
    // 取消点赞发起请求
    doCancelStar(commentSubject){
      this.checkLogin().then(()=>{
        let data = {
          commentSubjectId: commentSubject.id,
          groupFlag: this.groupFlag
        }
        this.$http.post(CommentSubjectStarUrl.cancelStar,data).then(()=>{
          commentSubject.isMeHasStared = false
          commentSubject.starCount -= 1
          this.removeStar(commentSubject)
        })
      })
    },
    // 在数据前添加一条点赞，主要用于 commentSubjectStar 发布成功后不用去后台请求数据，直接添加一条即可
    prependStar(commentSubject,commentSubjectStar){
      if(!commentSubject.latestCommentSubjectStars){
        this.$set(commentSubject,'latestCommentSubjectStars',{records: []})
      }
      commentSubject.latestCommentSubjectStars.records.unshift(commentSubjectStar)
    },
    // 取消点赞使用，移除当前用户已点赞的数据
    removeStar(commentSubject){
      if(commentSubject.latestCommentSubjectStars){
        let userId = this.userId || this.vuex_userInfo.id
        let a = commentSubject.latestCommentSubjectStars.records
        for (let i = 0; i < a.length; i++) {
          if(a[i].ownerUserId == userId){
            a.splice(i,1)
            return
          }
        }
      }
    },

    // 回复的点赞或取消
    replyStarOrCancel(commentHierarchical){
      if (commentHierarchical.isMeHasStared) {
        // 最后面的参数 true 表示立即执行
        this.$u.debounce(()=>{this.replyDoCancelStar(commentHierarchical)}, 800,true)
      }else {
        this.$u.debounce(()=>{this.replyDoStar(commentHierarchical)}, 800,true)
      }
    },
    // 回复的点赞发起请求
    replyDoStar(commentHierarchical){
      this.checkLogin().then(()=>{
        let data = {
          commentHierarchicalId: commentHierarchical.id,
          groupFlag: this.groupFlag
        }
        this.$http.post(CommentHierarchicalStarUrl.addStar,data).then((res)=>{
          commentHierarchical.isMeHasStared = true
          commentHierarchical.starCount += 1
          this.replyPrependStar(commentHierarchical,res.data)
        })
      })
    },
    // 回复的取消点赞发起请求
    replyDoCancelStar(commentHierarchical){
      this.checkLogin().then(()=>{
        let data = {
          commentHierarchicalId: commentHierarchical.id,
          groupFlag: this.groupFlag
        }
        this.$http.post(CommentHierarchicalStarUrl.cancelStar,data).then(()=>{
          commentHierarchical.isMeHasStared = false
          commentHierarchical.starCount -= 1
          this.replyRemoveStar(commentHierarchical)
        })
      })
    },
    // 回复的在数据前添加一条点赞，主要用于 commentHierarchicalStar 发布成功后不用去后台请求数据，直接添加一条即可
    replyPrependStar(commentHierarchical,commentHierarchicalStar){
      if(!commentHierarchical.latestCommentHierarchicalStars){
        this.$set(commentHierarchical,'latestCommentHierarchicalStars',{records: []})
      }
      commentHierarchical.latestCommentHierarchicalStars.records.unshift(commentHierarchicalStar)
    },
    // 回复的取消点赞使用，移除当前用户已点赞的数据
    replyRemoveStar(commentHierarchical){
      if(commentHierarchical.latestCommentHierarchicalStars){
        let userId = this.userId || this.vuex_userInfo.id
        let a = commentHierarchical.latestCommentHierarchicalStars.records
        for (let i = 0; i < a.length; i++) {
          if(a[i].ownerUserId == userId){
            a.splice(i,1)
            return
          }
        }
      }
    },

    detailReplyClick(commentSubject){
      this.$emit('detailReplyClick',commentSubject)
    },
    // 回复前面插入一条回复，主要省去一次后台请求，发布完回复后，直接展示
    replyPrependCommentHierarchical(commentHierarchical){
      this.commentSubject.commentCount += 1
      this.commentHierarchicalPage.total +=1
      this.commentHierarchicalList.unshift(commentHierarchical)
    },
    // 回复的回复前面插入一条回复，主要省去一次后台请求，发布完回复后，直接展示
    replyReplyPrependCommentHierarchical(commentHierarchical){
      let replyCommentHierarchical = this.getCommentHierarchicalById(commentHierarchical.parentId)
      if (!replyCommentHierarchical) {
        console.error("未能根据父级id获取到对应的风层级评论数据，这可能是参数传递错误，或方法使用错误,这会导致页面不会直接更新对应的")
        return
      }
      replyCommentHierarchical.commentCount += 1
      if(!replyCommentHierarchical.latestCommentHierarchicals){
        this.$set(replyCommentHierarchical,'latestCommentHierarchicals',{records: [],total: 0})
      }
      replyCommentHierarchical.latestCommentHierarchicals.total +=1
      replyCommentHierarchical.latestCommentHierarchicals.records.unshift(commentHierarchical)
    },
    getCommentHierarchicalById(id){
      for (let i = 0; i < this.commentHierarchicalList.length; i++) {
        if(this.commentHierarchicalList[i].id == id){
          return this.commentHierarchicalList[i]
        }
      }
      return null;
    },
    // 回复人头像点击事件
    replyAvatarClick(commentHierarchical){
      this.$emit('replyAvatarClick',commentHierarchical)
    },
    //回复的回复人头像点击事件， 每一条回复，子回复人头像点击事件
    replyReplyCommentHierarchicalAvatarClick(commentHierarchical,subCommentHierarchical){
      this.$emit('replyReplyCommentHierarchicalAvatarClick', {commentHierarchical,subCommentHierarchical})
    },
    // 回复的回复点击事件
    replyReplycommentReplyClick(commentHierarchical,subCommentHierarchical){
      this.$emit('replyReplycommentReplyClick', {commentHierarchical,subCommentHierarchical})
    },
    // 跳转到某一个回复的详情或说对回复的下级回复列表
    replyToAllReplyClick(commentHierarchical){
      this.$emit('replyToAllReplyClick', commentHierarchical)
    },
    // 回复的点赞头像点击事件
    replyStarAvatarClick(commentHierarchical,subCommentHierarchical){
      this.$emit('replyStarAvatarClick', {commentHierarchical,subCommentHierarchical})
    },
    // 回复的点赞全部点赞点击事件
    replyToAllStar(commentHierarchical){
      this.$emit('replyToAllStarClick', commentHierarchical)
    },
    // 对回复进行回复的点击事件
    replyReplyClick(commentHierarchical){
      this.$emit('replyReplyClick', commentHierarchical)
    }

  }
};
</script>

<style lang="scss" scoped>
.comment {
  padding: 30rpx;
  font-size: 32rpx;
  background-color: #ffffff;
  .top {
    display: flex;
    justify-content: space-between;
  }
  .left {
    display: flex;
    .heart-photo {
      image {
        width: 64rpx;
        height: 64rpx;
        border-radius: 50%;
        background-color: #f2f2f2;
      }
    }
    .user-info {
      margin-left: 10rpx;
      .name {
        color: #5677fc;
        font-size: 28rpx;
        margin-bottom: 4rpx;
      }
      .date {
        font-size: 20rpx;
        color: $u-light-color;
      }
    }
  }
  .right {
    display: flex;
    font-size: 20rpx;
    align-items: center;
    color: #9a9a9a;
    .detail-reply{
      margin-right: 15rpx;
    }
    .like {
      margin-left: 6rpx;
    }
    .num{
      font-size: 26rpx;
      color: #9a9a9a;
    }
  }
  .star-box{
    border-radius: 12rpx;
    margin-bottom: 12rpx;
    .star-box-border-bottom{
      border-bottom: solid 2rpx $u-border-color;

    }
    .all-star {
      padding-left: 20rpx;
      display: flex;
      color: #5677fc;
      align-items: center;
      .more {
        margin-left: 3rpx;
      }
    }
  }
  .highlight {
    color: #5677fc;
    .num{
      color: #5677fc;
    }
  }
}
.all-reply {
  margin-top: 10rpx;
  padding-top: 20rpx;
  background-color: #ffffff;
  .all-reply-top {
    margin-left: 20rpx;
    padding-left: 20rpx;
    border-left: solid 4rpx #5677fc;
    font-size: 30rpx;
    font-weight: bold;
  }
  .item {
    border-bottom: solid 2rpx $u-border-color;
  }

  .star-box{
    border-radius: 12rpx;
    margin-bottom: 12rpx;
    .star-box-border-bottom{
      border-bottom: solid 2rpx $u-border-color;

    }
    .all-star {
      padding-left: 20rpx;
      display: flex;
      color: #5677fc;
      align-items: center;
      .more {
        margin-left: 3rpx;
      }
    }
  }
  .reply-box {
    background-color: rgb(242, 242, 242);
    border-radius: 12rpx;
    .reply-box-item {
      padding: 20rpx;
      border-bottom: solid 2rpx $u-border-color;
      .username {
        font-size: 24rpx;
        color: #999999;
      }
      .text{
        margin-top: 10rpx;
        font-size: 26rpx;

        .reply{
          margin-left: 10rpx;
          color: #5677fc;
          font-size: 26rpx;
          .more {
            margin-left: 3rpx;
          }
        }
      }
    }
    .sub-all-reply {
      padding: 20rpx;
      display: flex;
      color: #5677fc;
      align-items: center;
      .more {
        margin-left: 6rpx;
      }
    }
  }
  .bottom {
    margin-top: 20rpx;
    display: flex;
    font-size: 24rpx;
    color: #9a9a9a;
    .reply {
      color: #5677fc;
      margin-left: 10rpx;
    }
  }
}
</style>
